	package com.ibeetl.eval.worker;

import java.util.Map;

import org.beetl.core.GroupTemplate;
import org.beetl.core.exception.ScriptEvalError;
import org.jdom2.CDATA;
import org.jdom2.Content;
import org.jdom2.Element;

import com.ibeetl.eval.EvalContext;
import com.ibeetl.eval.NodeWorker;
import com.ibeetl.eval.TreeNode;
import com.ibeetl.eval.Util;
import com.ibeetl.eval.XmlEvalException;

public class ScriptNodeWorker implements NodeWorker {

	public  TreeNode execute(Element ruleEle,EvalContext ctx){
		
		String name = ruleEle.getAttributeValue("name");//simple exression
		String script = getCDATA(ruleEle);
		Map paras = ctx.prepareNext();
		TreeNode current = ctx.goNext(name, ruleEle);
		paras.put("_root", current);
		Object ret = runScript(ctx,ruleEle,script,paras);
		current.setResult(ret);
		return current;
	}
	
	private Object runScript(EvalContext ctx,Element location,String script,Map<String,Object> paras) {
		try {
			GroupTemplate gt = ctx.getEvalEngine().gt;
			
			Map map= gt.runScript(script, paras);
			
			return map.get("return");
		} catch (ScriptEvalError e) {
			throw new XmlEvalException(location,e); 
		}
	}
	private String getCDATA(Element e){
		for(Content c : e.getContent()){
			 if (c instanceof CDATA) {  
                CDATA cdata = (CDATA) c;  
                return cdata.getText();
            } 
		}
		return null;
	}
	
	public  String getScript(Element ele){
		String express =  Util.getXMLContent(ele);
		return express;
	}

}
